<template>
  <a-row :gutter="10">
    <a-col :md="10" :sm="24">
      <a-card :bordered="false">

        <div style="background: #fff;padding-left:16px;height: 100%; margin-top: 5px">
          <a-alert type="info" :showIcon="true">
            <div slot="message">
              当前选择：<span v-if="this.currSelected.title">{{ getCurrSelectedTitle() }}</span>
              <a v-if="this.currSelected.title" style="margin-left: 10px" @click="onClearSelected">取消选择</a>
            </div>
          </a-alert>
          <a-input-search @search="onSearch" style="width:100%;margin-top: 10px" placeholder="请输入部门名称"/>
          <!-- 树-->
          <a-col :md="10" :sm="24">
            <!--组织机构-->
            <a-tree
              showLine
              :selectedKeys="selectedKeys"
              :checkStrictly="true"
              @select="onSelect"
              :dropdownStyle="{maxHeight:'200px',overflow:'auto'}"
              :treeData="departTree"
              :autoExpandParent="autoExpandParent"
              :expandedKeys="iExpandedKeys"
              @expand="onExpand"
            />
          </a-col>
        </div>
      </a-card>
    </a-col>
    <a-col :md="14" :sm="24">
      <a-card :bordered="false">
        <div class="file-list-wrapper">
          <!-- 操作按钮 -->
          <div class="table-operator">
            <!--            按钮权限 file:depart:add  v-has="'file:depart:add'"-->
            <a-button-group class="operate-group" v-if="hasUploadPermission">
              <a-button type="primary" icon="upload" id="uploadFileId" @click="upload()"
              >上传
              </a-button>
              <upload-modal ref="upload" :path="currentPath" :depart-file="true" :depart-id="this.currentOrg.id"
                            @ok="uplaodSuccess"></upload-modal>
              <a-button type="primary" icon="file" @click="addFolder()">新建文件夹
              </a-button>
              <DepartMkdir ref="mkdir" @ok="mkdirSuccess"></DepartMkdir>
              <a-button v-show="false" type="primary" icon="file">新建文件夹
              </a-button>
              <a-button v-show="false" type="primary" icon="file">新建文件夹
              </a-button>
            </a-button-group>

            <!-- 全局搜素文件 -->
            <a-input-search @search="handleSearchInputChange" placeholder="搜索您的文件" @clear="getTableDataByType"
                            v-model="fileNameSearch" class="select-file-input"/>
          </div>
          <div class="middle-wrapper">
            <div class="breadcrumb-wrapper">
              <div class="title">当前位置：</div>
              <a-breadcrumb separator="/">
                <a-breadcrumb-item class="ant-breadcrumb"
                ><a @click="resetParamOnThis(null)">{{ getCurrSelectedTitle() }}</a>

                </a-breadcrumb-item>

                <a-breadcrumb-item class="ant-breadcrumb"
                                   v-for="(item, index) in breadCrumbList"
                                   :key="index"
                ><a @click="resetParamOnThis(item.id)">{{ item.name }}</a>
                </a-breadcrumb-item>
              </a-breadcrumb>
            </div>
          </div>
          <!-- 文件列表-表格模式 -->
          <DepartFileTable
            :fileList="fileList"
            :loading="loading"
            :has="hasUploadPermission"
            @getTableDataByType="getTableDataByType"
            @getTableDataByTypeAndPath="getTableDataByTypeAndPath"
          ></DepartFileTable>
          <div class="pagination-wrapper">
            <div class="current-page-count">当前页{{ fileList.length }}条</div>
            <a-pagination
              v-model="pageData.currentPage"
              :total="pageData.total"
              :page-size-options="pageSizeOptions"
              show-size-changer
              :page-size="pageData.pageCount"
              @showSizeChange="handleSizeChange"
            >
              <template slot="buildOptionText" slot-scope="props">
                <span v-if="props.value !== '50'">{{ props.value }}条/页</span>
                <span v-if="props.value === '50'">全部</span>
              </template>
            </a-pagination>
          </div>
        </div>
      </a-card>
    </a-col>
  </a-row>
</template>

<script>
import {JeecgListMixin} from '@/mixins/JeecgListMixin'
import DepartFileTable from './components/DepartFileTable'
import {queryDepartTreeList, searchByKeywords} from '@/api/api'
import {getDepartFileList, getDepartPathTreeMap, makeDirDepart, searchDepartFile} from '@/api/file'
import {ROOT_PATH} from "../../global/globalConst";
import DepartMkdir from './components/DepartMkdir'
import UploadModal from './components/UploadModal'
import Vue from "vue";
import store from "../../components/jeecg/JVxeTable/mixins/vxe.web.socket.mixins";
import {USER_INFO} from '@/store/mutation-types'

export default {
  name: 'AeeDepartFileList',
  mixins: [JeecgListMixin],
  components: {
    DepartFileTable, DepartMkdir, UploadModal
  },
  data() {
    return {
      //*****右边 列表数据*****
      fileNameSearch: '',
      pageSizeOptions: ['10', '20', '30', '40', '50'],
      // loading: true, //  表格数据-loading
      fileList: [], //  表格数据-文件列表
      pageData: {
        currentPage: 1,
        pageCount: 10,
        total: 0
      },
      fileModel: 0,
      currentClickPath: null,
      pathTreeMap: Map,
      breadCrumbList: Array,
      hasUploadPermission: false,
      ////////////////////* 左边部门数据**********/
      iExpandedKeys: [],
      loading: false,
      autoExpandParent: true,
      currFlowId: '',
      currFlowName: '',
      disable: true,
      treeData: [],
      visible: false,
      departTree: [],
      hiding: true,
      model: {},
      dropTrigger: '',
      depart: {},
      // columns: columns,
      disableSubmit: false,
      selectedKeys: [],
      autoIncr: 1,
      currSelected: {},
      allTreeKeys: [],
      labelCol: {
        xs: {span: 24},
        sm: {span: 5}
      },
      wrapperCol: {
        xs: {span: 24},
        sm: {span: 16}
      },
      graphDatasource: {
        nodes: [],
        edges: []
      },
      orgCategoryDisabled: false,

    }
  },
  computed: {

    // breadCrumbList() {
    //   return this.getPathTree(this.currentPath);
    // },
    //  当前查看的文件路径
    currentPath: {
      get() {
        return this.currentClickPath
      },
      set() {
        return this.currentClickPath
      }
    },
    // 文件类型
    currentFileType: {
      get() {
        return this.FILE_TYPE.ALL
      },
      set() {
        return this.FILE_TYPE.ALL
      }
    },
    // 文件查看模式 0列表模式 1网格模式 2 时间线模式
    currentFileModel() {
      return this.FILE_MODEL.TABLE
    },
  },
  watch: {
    currentPath() {
      this.getTableDataByType()
      this.setPageCount()
    },
    // currentFileType(newValue, oldValue) {
    //   if (oldValue === this.FILE_TYPE.IMAGE && this.fileModel().isTimeLine()) {
    //     this.$store.commit('changeFileModel', this.FILE_MODEL.TABLE)
    //   }
    //   this.getTableDataByType()
    //   this.setPageCount()
    // },
    // 监听文件查看模式
    // currentFileModel() {
    //   this.getTableDataByType()
    //   this.setPageCount()
    // }
  },
  created() {
    // this.currFlowId = this.$route.params.id
    // this.currFlowName = this.$route.params.name
    // this.loadTree()
    // this.setPageCount()
    // this.getTableDataByType()
  },
  methods: {
    uplaodSuccess() {
      this.getTableDataByType();
    },
    mkdirSuccess(dirName) {
      //创建目录
      makeDirDepart({name: dirName, pid: this.currentPath, departId: this.currentOrg.id}).then(res => {
        if (res.success) {
          this.getDepartPathTree();
          this.getTableDataByType();
          this.$refs.mkdir.close();
        } else {
          this.$message.error(res.message);
        }
      })
    },
    // 传入目录id
    getPathTree(pid) {
      if (pid === 'null') {
        pid = ROOT_PATH;
      }
      let list = []
      let id = pid
      while (id) {
        list.push(this.pathTreeMap[id])
        id = this.pathTreeMap[id].pid
      }
      return list.reverse();
    },
    getDepartFileListByRoot(record) {
      this.currentClickPath = null;
      this.currentOrg = record;
      console.log(this.currentOrg);
      this.computeHaspermission(this.currentOrg.orgCode);
      this.getDepartPathTree();
      this.getTableDataByType();
    },
    computeHaspermission(value) {
      let userOrgCode = Vue.ls.get(USER_INFO).orgCode;
      let lengthorg = userOrgCode.length;
      console.log(value);
      this.hasUploadPermission = value != null && value.substring(0, lengthorg) === userOrgCode;
    },
    getDepartPathTree() {
      //
      getDepartPathTreeMap({departId: this.currentOrg.id}).then(res => {
        if (res.success) {
          this.pathTreeMap = res.result;
          this.breadCrumbList = this.getPathTree(this.currentClickPath)
        } else {
          this.$message.error("加载目录出错");
        }
      });

    },
    resetParamOnThis(pid) {

      this.getTableDataByTypeAndPath(pid);
    },
    upload() {
      this.$refs.upload.show();
    },
    addFolder() {
      if (this.currentOrg == null) {
        this.$message.error("请选择一个部门");
        return false;
      }
      this.$refs.mkdir.show();

    },
    handleSearchInputChange(content) {
      this.loading = true
      searchDepartFile({
        pageNo: this.pageData.currentPage,
        pageSize: this.pageData.pageCount,
        content: content
      }).then(res => {
        this.reflushFileList(res.result)
      }).catch(err => {
        console.error(err)
        this.$message.error("服务器正忙")
      })

    },
    handleSearchClick() {
    },

//*********左边部门数据方法************//
    loadData() {
      this.refresh();
    },
    refresh() {
      this.loading = true
      this.loadTree()
    },
    loadTree() {
      var that = this
      that.treeData = []
      that.departTree = []
      queryDepartTreeList().then((res) => {
        if (res.success) {
          //部门全选后，再添加部门，选中数量增多
          this.allTreeKeys = [];
          for (let i = 0; i < res.result.length; i++) {
            let temp = res.result[i]
            that.treeData.push(temp)
            that.departTree.push(temp)
            that.setThisExpandedKeys(temp)
            that.getAllKeys(temp);
            // //console.log(temp.id)
          }
          this.loading = false
        }
      })
    },
    getAllKeys(node) {
      // //console.log('node',node);
      this.allTreeKeys.push(node.key)
      if (node.children && node.children.length > 0) {
        for (let a = 0; a < node.children.length; a++) {
          this.getAllKeys(node.children[a])
        }
      }
    },
    getCurrSelectedTitle() {
      return !this.currSelected.title ? '' : this.currSelected.title
    },
    onClearSelected() {
      this.hiding = true
      this.checkedKeys = []
      this.currSelected = {}
      this.selectedKeys = []
      this.currentOrg = null;
    },
    onSearch(value) {
      let that = this
      if (value) {
        searchByKeywords({keyWord: value}).then((res) => {
          if (res.success) {
            that.departTree = []
            for (let i = 0; i < res.result.length; i++) {
              let temp = res.result[i]
              that.departTree.push(temp)
            }
          } else {
            that.$message.warning(res.message)
          }
        })
      } else {
        that.loadTree()
      }

    },
    onExpand(expandedKeys) {
      //console.log('onExpand', expandedKeys)
      this.iExpandedKeys = expandedKeys
      this.autoExpandParent = false
    },
    onSelect(selectedKeys, e) {
      //console.log('selected', selectedKeys, e)
      this.hiding = false
      let record = e.node.dataRef
      //console.log('onSelect-record', record)
      this.currSelected = Object.assign({}, record)
      this.model = this.currSelected
      this.selectedKeys = [record.key]
      this.model.parentId = record.parentId
      this.getDepartFileListByRoot(record);

    },
    setThisExpandedKeys(node) {
      //只展开一级目录
      if (node.children && node.children.length > 0) {
        this.iExpandedKeys.push(node.key)
        //下方代码放开注释则默认展开所有节点
        /**
         for (let a = 0; a < node.children.length; a++) {
            this.setThisExpandedKeys(node.children[a])
          }
         */
      }
    },
    //********右边数据展示************//
    /**
     * 表格数据获取相关事件
     */
    reflushFileList(res) {
      this.loading = false
      this.fileList = res.records
      //console.log(this.fileList);
      this.pageData.total = res.total
    },
    // 调整分页大小
    setPageCount() {
      this.pageData.currentPage = 1
      this.pageData.pageCount = 10
    },
    // 获取文件列表数据
    getTableDataByType() {
      this.batchOperate = false
      this.loading = true
      // 全部文件
      this.showFileList()
    },
    // 获取文件列表数据
    getTableDataByTypeAndPath(path) {

      this.currentClickPath = path;
      this.getDepartPathTree();
      this.getTableDataByType();
    },
    // 获取当前路径下的文件列表
    showFileList() {
      let data = {
        pageNo: this.pageData.currentPage,
        pageSize: this.pageData.pageCount
      }
      if (this.currentPath != null) {
        data.pid = this.currentPath
      }
      if (this.currentOrg != null) {
        data.departId = this.currentOrg.id;
      }

      getDepartFileList(data).then((res) => {
        this.reflushFileList(res.result)
      }).catch(err => {
        this.$message.error("服务器正忙")
      })
    },
    // 分页组件 当前页码改变
    handleCurrentChange(currentPage) {
      this.pageData.currentPage = currentPage
      this.getTableDataByType()
    },
    handleSizeChange(current, pageCount) {
      this.pageData.pageCount = pageCount
      this.pageData.currentPage = current
      this.getTableDataByType()
    },

    // 获取搜索文件结果列表
    getSearchFileList(filename) {
      this.loading = true
      searchFile({
        currentPage: this.pageData.currentPage,
        pageCount: this.pageData.pageCount,
        filename: filename
      }).then(res => {
        this.reflushFileList(res)
      }).catch(err => {
        //console.error(err)
        this.$message.error("服务器正忙")
      })
    },

  },


}
</script>
<style lang="less" scoped>
@import '~@assets/less/common.less';

.breadcrumb-wrapper {
  padding: 0;
  height: 30px;
  line-height: 30px;
  display: flex;


}

.breadcrumb-wrapper.title {
  height: 30px;
  line-height: 30px;
}

.ant-breadcrumb {
  height: 30px;
  line-height: 30px;
}

.file-list-wrapper {
  a-page-header {
    padding: 0
  }

  .middle-wrapper {
    margin-bottom: 8px
  }

  .pagination-wrapper {
    position: relative;
    border-top: 1px solid #DCDFE6;
    height: 44px;
    line-height: 44px;
    text-align: center;

    .current-page-count {
      position: absolute;
      left: 16px;
      height: 32px;
      line-height: 32px;
      font-size: 13px;
      color: #606266
    }
  }


}


.operation-menu-wrapper.file-type-6 {
  margin: 8px 0;
  justify-content: flex-end;
}

.operation-menu-wrapper {
  padding: 16px 0;
  display: flex;
  justify-content: space-between;
  align-items: center;

}

.operate-group {
  flex: 1;
  align-items: center;
}


.change-image-model,
.change-file-model {
  margin-right: 8px
}


.batch-opera-btn {
  margin-right: 8px
}


.select-file-input {
  margin-right: 8px;
  width: 200px;

  .a-icon-search {
    cursor: pointer;
    font-size: 16px;

    &:hover {
      color: primary;
    }
  }
}

.select-column {
  width: 230px;
  //padding-top: 8px;
}
</style>
